package com.stm.bi.executor;

import com.stm.framework.snowflake.Snowflake;
import org.springframework.stereotype.Component;
import jakarta.annotation.Resource;
import com.stm.framework.dto.Response;
import com.stm.bi.repository.report.SubjectRepository;
import com.stm.bi.dto.cmd.SubjectAdd;
import com.stm.bi.dto.cmd.SubjectUpd;
import com.stm.framework.core.util.StringUtil;
import com.stm.bi.dto.query.SubjectListQry;
import com.stm.bi.dto.vo.SubjectVO;

import java.util.List;

/**
 * 科目-保存执行器
 *
 * @author qinyongjie
 * @date 2025-05-22
 */
@Component
public class SubjectSaveExe {
    @Resource
    private SubjectRepository subjectRepository;

    /**
     * 保存
     *
     * @param subjectAdd
     */
    public Response create(SubjectAdd subjectAdd) {
        // 校验参数
        String errorMsg = validateSubjectName(subjectAdd.getName(), null);
        if (StringUtil.isNotEmpty(errorMsg)) {
            return Response.failure(errorMsg);
        }

        Long id = Snowflake.getInstance().nextId();
        subjectAdd.setId(id);
        
        boolean res = subjectRepository.create(subjectAdd);
        return Response.build(res);
    }

    /**
     * 更新
     *
     * @param subjectUpd
     */
    public Response update(SubjectUpd subjectUpd) {
        // 校验参数
        String errorMsg = validateSubjectName(subjectUpd.getName(), subjectUpd.getId());
        if (StringUtil.isNotEmpty(errorMsg)) {
            return Response.failure(errorMsg);
        }

        boolean res = subjectRepository.update(subjectUpd);
        return Response.build(res);
    }

    /**
     * 校验科目名称是否重复，返回错误信息，无错误返回null
     *
     * @param name 科目名称
     * @param id 科目ID，更新时传入，新增时为null
     * @return 错误信息，无错误返回null
     */
    private String validateSubjectName(String name, Long id) {
        // 检查科目名称重名
        if (StringUtil.isNotEmpty(name)) {
            SubjectListQry nameQuery = new SubjectListQry();
            nameQuery.setName(name);
            List<SubjectVO> existingSubjects = subjectRepository.selectList(nameQuery);
            if (existingSubjects != null && !existingSubjects.isEmpty()) {
                // 如果是更新操作，且只找到了一条记录，且该记录就是当前正在更新的记录，则不算重名
                if (id != null && existingSubjects.size() == 1 && id.equals(existingSubjects.getFirst().getId())) {
                    return null;
                }
                return "科目名称已存在，请修改后重新提交";
            }
        }
        return null;
    }
}
